﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace SPM.DAL
{
    public class DataFactory
    {
        private IDbConnection CreateConnection()
        {
            //SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SPM"].ConnectionString);
            string cs = @"Data Source = localhost\sqlexpress;Initial catalog = SPM;Integrated Security = True";
            SqlConnection conn = new SqlConnection(cs);
            return conn;
        }

        public IDbCommand CreateCommand()
        {
            return CreateCommand(String.Empty, CreateConnection());
        }

        public IDbCommand CreateCommand(string commandText)
        {
            return CreateCommand(commandText, CreateConnection());
        }

        public IDbCommand CreateCommand(string
            commandText, IDbConnection connection)
        {
            return new SqlCommand(commandText,
                (SqlConnection)connection);
        }

        //implementei usando o MAX por que não tive sucesso com o @@identity
        public int GetLastIdentity(string tabela)
        {
            string commandText = String.Format("SELECT MAX(id{0}) FROM {0}", tabela);
            IDbCommand comando = CreateCommand(commandText);
            int ultId = 0;
            try
            {
                comando.Connection.Open();
                object obj = comando.ExecuteScalar();
                if (obj.Equals(DBNull.Value))
                    ultId = -1;
                else
                    ultId = Convert.ToInt32(obj);
            }
            finally
            {
                comando.Dispose();
            }
            return ultId;
        }
    }
}
